#!/bin/sh

set -eu

set --
set -- "$@" -machine pc -smp "${VM_CPU:?}" -m "${VM_RAM:?}"
set -- "$@" -device cirrus-vga -display vnc=:0 -serial stdio -monitor unix:/run/qemu-monitor,server,nowait
set -- "$@" -device rtl8139,netdev=n0 -netdev user,id=n0,ipv4=on,ipv6=off,net=10.0.2.0/24,host=10.0.2.2,dns=10.0.2.3,dhcpstart=10.0.2.15,hostfwd=tcp::2323-:23,hostfwd=tcp::5151-:51,hostfwd=tcp::3389-:3389,"${VM_NET_EXTRA_OPTIONS?}"
set -- "$@" -device ide-hd,id=disk0,bus=ide.0,drive=disk0 -blockdev driver=qcow2,node-name=disk0,file.driver=file,file.filename=/var/lib/qemu/disk/win2000.qcow2
set -- "$@" -usb -device usb-tablet
set -- "$@" -k "${VM_KEYBOARD:?}"

if [ "${VM_KVM:?}" = true ] && [ -c /dev/kvm ]; then
	set -- "$@" -accel kvm -cpu host
else
	set -- "$@" -accel tcg
fi

disk_i=1
for disk in /var/lib/qemu/disk/*.qcow2 /var/lib/qemu/disk/*.qcow2c; do
	{ [ -f "${disk:?}" ] && [ "${disk:?}" = "${disk%/win2000.qcow2}" ]; } || continue
	set -- "$@" -device ide-hd,id=disk"${disk_i:?}",bus=ide.$((disk_i / 2)),drive=disk"${disk_i:?}" -blockdev driver=qcow2,node-name=disk"${disk_i:?}",file.driver=file,file.filename="${disk:?}"
	disk_i="$((disk_i + 1))"
done

cd_i="${disk_i:?}"
for cd in /var/lib/qemu/cd/*; do
	[ -f "${cd:?}" ] || continue
	set -- "$@" -device ide-cd,id=cd"${cd_i:?}",bus=ide.$((cd_i / 2)),drive=cd"${cd_i:?}" -blockdev driver=raw,node-name=cd"${cd_i:?}",file.driver=file,file.filename="${cd:?}",read-only=on
	cd_i="$((cd_i + 1))"
done

floppy_i=0
for floppy in /var/lib/qemu/floppy/*; do
	[ -f "${floppy:?}" ] || continue
	set -- "$@" -device floppy,id=floppy"${floppy_i:?}",bus=floppy-bus.$((floppy_i / 2)),drive=floppy"${floppy_i:?}" -blockdev driver=raw,node-name=floppy"${floppy_i:?}",file.driver=file,file.filename="${floppy:?}",read-only=on
	floppy_i="$((floppy_i + 1))"
done

if [ "${cd_i:?}" -gt 0 ]; then
	set -- "$@" -boot order=dc,menu=on,splash-time=5000
fi

cd /var/lib/qemu/
exec 2>&1
exec /usr/bin/qemu-system-x86_64 "$@"
